<?php

namespace App\Models;

// use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;
use DB;

class Cart extends BaseModel
{
    //

    protected $primaryKey = 'id';

    protected $casts = [
        'created_at' => 'Y-m-d H:i:s',
        'updated_at' => 'Y-m-d H:i:s',
    ];

    protected $fillable = ['member_id', 'goods_id', 'sku_id', 'num', 'price', 'discount_amount', 'total_amount', 'created_at', 'updated_at'];

    /**
     * 商品信息
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function goods()
    {
        return $this->hasOne(Goods::class, 'id', 'goods_id');
    }

    /**
     * 商品信息
     * @return \Illuminate\Database\Eloquent\Relations\hasOne
     */
    public function goodsSku()
    {
        return $this->hasOne(GoodsSku::class, 'id', 'sku_id');
    }


    public static function getList(array $attributes)
    {
        extract($attributes);

        $where = ['member_id' => $member_id];

        $model = Cart::where($where);

        $total = $model->count();

        $model->orderBy('updated_at', 'DESC');

        $model->with('goods', 'goodsSku');
        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();

            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            return self::formatBody(['list' => $data]);
        }
    }

    public static function countGoodsNum(array $attributes)
    {
        extract($attributes);

        $where = ['member_id' => $member_id];

        $model = Cart::where($where);

        $model->with('goods', 'goodsSku');

        $data = $model->get();

        $count = 0;

        if (!$data)
        {
            $count = 0;
        }

        foreach ($data->toArray() as $val)
        {
            if (isset($val['num']) && $val['num'])
            {
                $count += $val['num'];
            }
        }

        return $count;
    }

    public static function add(array $attributes)
    {
        extract($attributes);

        $goods = Goods::where('id', $goods_id)->first();

        if (!$goods->putaway)
        {
            return self::formatError(400 , '更新购物车失败：商品已下架');
        }

        $goods_sku = GoodsSku::where('id', $sku_id)->with('stock')->first();

        if (!$goods_sku)
        {
            return self::formatError(400 , '更新购物车失败：货品不存在');
        }

        if ($num > $goods_sku->stock->quantity)
        {
            return self::formatError(400 , '更新购物车失败：库存不足');
        }

        DB::beginTransaction();

        // 此处应该走事务
        try {
            // 合并购物车
            $cart = Cart::where('member_id', $member_id)->where('goods_id', $goods_id)->where('sku_id', $sku_id)->first();

            if ($cart)
            {
                if (isset($type) && $type=='fastedit')
                {
                    $cart->num = $num;
                }
                else
                {
                    $cart->num += $num;
                }

                $cart->total_amount = $goods_sku->price * $num;

                $cart->save();
            }
            else
            {
                $params = [
                    'member_id' => $member_id,
                    'goods_id' => $goods_id,
                    'sku_id' => $sku_id,
                    'num' =>$num,
                    'price' => $goods_sku->price,
                    'discount_amount' => 0,
                    'total_amount' => $goods_sku->price * $num,
                ];

                $cart = Cart::create($params);
            }

            DB::commit();

        } catch (\Exception $exception) {

            DB::rollback();

            return self::formatError(400 , '更新购物失败:'.$exception->getMessage());
        }

        return $cart;
    }

    public static function deleteCart(array $attributes)
    {
        extract($attributes);

        DB::beginTransaction();

        // 此处应该走事务
        try {

            if (is_array($cart_id))
            {
                $res = Cart::where('member_id', $member_id)->whereIn('id', $cart_id)->delete();
            }
            else
            {
                $res = Cart::where('member_id', $member_id)->where('id', $cart_id)->delete();
            }

            DB::commit();

        } catch (\Exception $exception) {

            DB::rollback();

            return self::formatError(400 , '删除购物失败:'.$exception->getMessage());
        }

        return $res;
    }

}
